package com.beiding.jsonanalyzer.analyze;

import java.io.*;
import java.net.URL;

public class ResourceUtils {

    public static String read(Object input) {
        try {
            return read0(input);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static String read0(Object input) throws Exception {
        if (input instanceof File) {
            try {
                FileInputStream fileInputStream = new FileInputStream((File) input);
                String s = read0(fileInputStream);
                fileInputStream.close();
                return s;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else if (input instanceof Reader) {
            char[] buff = new char[512];
            int len;
            StringBuilder builder = new StringBuilder();
            Reader reader = (Reader) input;
            while ((len = reader.read(buff)) != -1) {
                builder.append(buff, 0, len);
            }
            return builder.toString();
        } else if (input instanceof InputStream) {
            return read0(new InputStreamReader((InputStream) input));
        } else if (input instanceof URL) {
            return read0(((URL) input).openStream());
        } else {
            throw new RuntimeException("不支持的输入:" + input);
        }
    }

    public static void write(String content,Object output) {
        try {
            write0(content, output);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static void write0(String content, Object output) throws Exception {
        if (output instanceof File) {
            try {
                FileOutputStream stream = new FileOutputStream((File) output);
                write0(content, stream);
                stream.flush();
                stream.close();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else if (output instanceof Writer) {
            ((Writer) output).write(content);
            ((Writer) output).flush();
        } else if (output instanceof OutputStream) {
            write0(content, new OutputStreamWriter((OutputStream) output));
        } else {
            throw new RuntimeException("不支持的输入");
        }
    }

}
